package com.zidian.study.activity;

import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.Editable;
import android.text.TextWatcher;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;

import com.bumptech.glide.Glide;
import com.google.gson.Gson;
import com.yuyh.library.imgsel.ImageLoader;
import com.yuyh.library.imgsel.ImgSelActivity;
import com.yuyh.library.imgsel.ImgSelConfig;
import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.callback.StringCallback;
import com.zidian.student.trucks.R;
import com.zidian.study.adapter.ImagePikerAdapter;
import com.zidian.study.bean.Bimp;
import com.zidian.study.event.DeleteImageEvent;
import com.zidian.study.globa.BaseEntity;
import com.zidian.study.globa.Constant;
import com.zidian.study.globa.ToolBarActivity;
import com.zidian.study.utils.FileUtils;
import com.zidian.study.utils.FileUtilsOld;
import com.zidian.study.utils.GetUserInfo;
import com.zidian.study.utils.ImageFactory;
import com.zidian.study.utils.ProgressBarBlackUtil;
import com.zidian.study.utils.ToastUtil;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;
import okhttp3.Call;


/**
 * Created by Administrator on 2016/9/13 0013.
 * 意见反馈界面
 */
public class PersonOpitionActivity extends ToolBarActivity implements TextWatcher {
    @Bind(R.id.photo_preview_list_rv)
    RecyclerView photoPreviewListRv;
    @Bind(R.id.opition_confrim)
    Button confirmBtn;
    @Bind(R.id.opition_edit)
    EditText optionContent;

    private ImagePikerAdapter adapter;
    private List<String> images;
    private ImageFactory imageFactory;

    private static final int REQUEST_CODE = 0;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_person_opition);
        ButterKnife.bind(this);
        setTitle("意见反馈");
        imageFactory = new ImageFactory();
        images = new ArrayList<>();
        initView();
    }

    public void initView() {
        optionContent.addTextChangedListener(this);
        adapter = new ImagePikerAdapter(this);
        adapter.setImageCount(1);
        RecyclerView.LayoutManager layoutManager = new LinearLayoutManager(this, LinearLayoutManager.HORIZONTAL, false);
        photoPreviewListRv.setLayoutManager(layoutManager);
        photoPreviewListRv.setAdapter(adapter);
        adapter.setOnItemClickListener(new ImagePikerAdapter.OnItemClickListener() {
            @Override
            public void onClick(int position) {
                if (images.size() == position) {
                    pickImages();
                } else {
                    Intent intent = new Intent(context, NewPhotoActivity.class);
                    intent.putExtra("imagePath", images.get(position));
                    intent.putExtra("position", position);
                    startActivity(intent);
                }
            }
        });
        EventBus.getDefault().register(this);

    }

    @OnClick(R.id.opition_confrim)
    public void confirm() {
        confirmBtn.setEnabled(false);
        upDataToOpition();
    }

    /**
     * 图片加载器
     */
    private ImageLoader loader = new ImageLoader() {
        @Override
        public void displayImage(Context context, String path, ImageView imageView) {
            Glide.with(context).load(path).into(imageView);
        }
    };

    /**
     * 图片选择器
     */
    private void pickImages() {
        ImgSelConfig config = new ImgSelConfig.Builder(loader)
                // 是否多选
                .multiSelect(false)
                // 确定按钮背景色
                .btnBgColor(Color.GRAY)
                // 确定按钮文字颜色
                .btnTextColor(Color.BLUE)
                // 使用沉浸式状态栏
//                .statusBarColor(Color.parseColor("#3F51B5"))
                // 返回图标ResId
                .backResId(android.support.v7.appcompat.R.drawable.abc_ic_ab_back_mtrl_am_alpha)
                .title("图片")
                .titleColor(Color.WHITE)
                .titleBgColor(Color.parseColor("#25bf7f"))
                .cropSize(1, 1, 800, 480)
                .needCrop(false)
                // 第一个是否显示相机
                .needCamera(false)
                // 最大选择图片数量
                .maxNum(5)
                .build();

        ImgSelActivity.startActivity(this, config, REQUEST_CODE);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == REQUEST_CODE && resultCode == RESULT_OK && data != null) {
            List<String> pathList = data.getStringArrayListExtra(ImgSelActivity.INTENT_RESULT);

            for (String path : pathList) {
                images.add(path);
            }
            adapter.setImages(images);
        }
    }

    /**
     * 压缩图片
     *
     * @param images
     * @return
     */
    private List<String> compressImages(List<String> images) {
        List<String> newImages = new ArrayList<>();
        for (int i = 0; i < images.size(); i++) {
            String newPath = FileUtils.createRootPath(this) + "/" + System.currentTimeMillis() + ".jpg";
            try {
                imageFactory.compressAndGenImage(images.get(i),
                        newPath, 100, false);
                newImages.add(newPath);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        return newImages;
    }

    /**
     * 删除图片
     *
     * @param event
     */
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void deleteImage(DeleteImageEvent event) {
        if (event.getPosition() != -1) {
            images.remove(event.getPosition());
            adapter.setImages(images);
        }

    }

    @Override
    public void afterTextChanged(Editable s) {

    }

    @Override
    public void beforeTextChanged(CharSequence s, int start, int count,
                                  int after) {

    }

    @Override
    public void onTextChanged(CharSequence s, int arg1, int arg2, int arg3) {

        boolean opition = optionContent.getText().toString().trim().length() > 0;

        if (opition) {
            confirmBtn.setEnabled(true);
            confirmBtn.setBackgroundResource(R.drawable.bg_commit_btn_normal);
        } else {
            confirmBtn.setEnabled(false);
            confirmBtn.setBackgroundResource(R.drawable.bg_commit_btn_selector);
        }

    }

    private void upDataToOpition() {
        String loginUrl = Constant.URL_GOAL + "suggestionFeedback/add";

        HashMap map = new HashMap();
        map.put("feedbackId", GetUserInfo.getStudentId(context));
        map.put("token", GetUserInfo.getToken(context));
        map.put("feedbackInformation", optionContent.getText().toString().trim());
        map.put("type", "1");
        HashMap<String, File> files = new HashMap<>();
        List<String> newImages = compressImages(images);
        for (int i = 0; i < newImages.size(); i++) {
            files.put("file" + i, new File(images.get(i)));
        }

        ProgressBarBlackUtil.loadShow(context);
        OkHttpUtils.post().
                url(loginUrl).
                files("file", files).params(map).
                build().
                connTimeOut(20000).
                writeTimeOut(20000).
                readTimeOut(20000).
                execute(new StringCallback() {
                    @Override
                    public void onError(Call call, Exception e, int id) {
                        ProgressBarBlackUtil.loadCancel();
                        ToastUtil.showToast(context, "提交失败");
                        finish();
                    }

                    @Override
                    public void onResponse(String response, int id) {
                        Gson gson = new Gson();
                        BaseEntity base = gson.fromJson(response, BaseEntity.class);
                        if (base.isSuccess()) {
                            ProgressBarBlackUtil.loadCancel();
                            ToastUtil.showToast(context, "提交成功");
                            finish();
                        }
                    }
                });
    }


}
